package com.qf.controller;

import com.qf.entity.LoginHistory;
import com.qf.entity.User;
import com.qf.service.LoginHistoryService;
import com.qf.service.UserService;
import com.qf.service.impl.LoginHistoryServiceImpl;
import com.qf.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;

/**
 * @author zdl
 * @date 2025/1/19
 */
@WebServlet("/loginUrl")
public class LoginController extends HttpServlet {
    private UserService userService = new UserServiceImpl();
    private LoginHistoryService loginHistoryService = new LoginHistoryServiceImpl();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");

        String username = req.getParameter("username");
        String password = req.getParameter("password");
        User user = userService.login(username, password);
        req.getSession().setAttribute("loginUser",user);
        LoginHistory loginHistory = new LoginHistory();
        loginHistory.setUserId(user.getUserId());
        loginHistory.setIp(req.getRemoteAddr());
        loginHistory.setCreateTime(new Date());
        loginHistoryService.addLoginHistory(loginHistory);
        resp.sendRedirect("/404.jsp");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
